package com.educate.service.impl;

import com.educate.common.exception.Asserts;
import com.educate.common.security.AccountUser;
import com.educate.pojo.User;
import com.educate.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author yjj
 * @date 2021/11/6
 * @description: 验证用户名，并返回需要验证的数据
 */

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getUserInfoByUsername(username);
        if(user == null){
            Asserts.fail("账号或密码不正确！");
        }
        return new AccountUser(user.getId(),user.getUsername(),user.getPassword(),getUserAuthority(user.getId()));

    }
    /*
    获取不同用户的菜单操作权限
     */
    public List<GrantedAuthority> getUserAuthority(Long userId){
        String authorityInfo = userService.getUserAuthorityInfo(userId);
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authorityInfo);
    }
}
